#include<stdio.h>
#include<assert.h>
#include"util.h"
#include"table.h"



struct item* newitem(void* key, void* value, struct item* next, void* prevtop)
{
	struct item* ptr = (struct item*)sec_malloc(sizeof(struct item));
	ptr->key = key;
	ptr->value = value;
	ptr->next = next;
	ptr->prevtop = prevtop;

	return ptr;
}
struct table* newtable()
{
	int i=0;
	struct table* ptr = (struct table*)sec_malloc(sizeof(struct table));
	ptr->top = NULL;

	//初始化哈希表
	for(i=0;i<CM_TABSIZE;i++)
		ptr->hashtable[i] = NULL;
	
	return ptr;
}
void table_insert(struct table* t, void* key, void* value)
{
	assert(t && key);
	unsigned int pos = (unsigned int)key % CM_TABSIZE;

	t->hashtable[pos] = newitem(key, value, t->hashtable[pos], t->top);
	t->top = key;
}
void* table_lookup(struct table* t, void* key)
{
	assert(t && key);
	unsigned int pos = (unsigned int)key % CM_TABSIZE;
	struct item* cur;

	for(cur=t->hashtable[pos]; cur !=NULL; cur = cur->next)
					if(cur->key == key)
									return cur->value;
	return NULL;
}


void* table_pop(struct table* t)
{
	assert(t);
	void* key = t->top;
	unsigned int pos = (unsigned int)key % CM_TABSIZE;
	struct item* Topop = t->hashtable[pos];
	assert(Topop);	//保证对应item项不为空
	t->hashtable[pos] = Topop->next;
	t->top = Topop->prevtop;

	return key;
}

//DFS 
void table_dump(struct table* t, void (*show)(void* key, void* value))
{
	void* key = t->top;
	unsigned int pos = (unsigned int)key % CM_TABSIZE;
	struct item* cur = t->hashtable[pos];
	if(cur == NULL)
					return ;
	show(cur->key, cur->value);
	
	t->hashtable[pos] = cur->next;
	t->top = cur->prevtop;

	table_dump(t, show);

	t->hashtable[pos] = cur;
	t->top = cur;
}
